// Modules to control application life and create native browser window
const { app, BrowserWindow, Tray, Menu, nativeImage, shell, ipcMain, dialog } = require('electron')
const path = require('node:path')
const fs = require('fs');

// 设置文件路径
const SETTINGS_PATH = path.join(app.getPath('userData'), 'settings.json');
// 检查是否已有实例运行
const gotTheLock = app.requestSingleInstanceLock();

if (!gotTheLock) {
  // 如果已有实例运行，则退出当前实例
  app.quit();
} else {
  // 首次启动或没有其他实例运行时
  app.on('second-instance', (event, commandLine, workingDirectory) => {
    if (mainWindow) {
      if (mainWindow.isMinimized()) mainWindow.restore();
      mainWindow.show();
      mainWindow.focus();
    }
  });
  let mainWindow;
  let tray;


  function createWindow() {
    // Create the browser window.
    mainWindow = new BrowserWindow({
      width: 1200,
      height: 800,
      //隐藏控制栏
      frame: false,
      webPreferences: {
        preload: path.join(__dirname, 'preload.js'),
        nodeIntegration: true,
        contextIsolation: false
      },
      icon: path.join(__dirname, 'images/icon.png') // 请确保有此图标文件
    })
    // and load the index.html of the app.
    mainWindow.loadFile('index.html')
    //隐藏原菜单栏
    mainWindow.setMenu(null)
    // Open the DevTools.
    // mainWindow.webContents.openDevTools()

    // 处理渲染进程的窗口控制请求
    ipcMain.on('window-control', (event, action) => {
      switch (action) {
        case 'minimize':
          mainWindow.minimize();
          break;
        case 'maximize':
          mainWindow.isMaximized() ? mainWindow.unmaximize() : mainWindow.maximize();
          break;
        case 'close':
          mainWindow.close();
          break;
      }
    })
    // 监听全屏切换请求
    ipcMain.on('toggle-fullscreen', () => {
      const isFullscreen = mainWindow.isFullScreen();
      mainWindow.setFullScreen(!isFullscreen);

      // 通知渲染进程全屏状态
      mainWindow.webContents.send('fullscreen-status', !isFullscreen);
    });

    // 监听退出全屏请求
    ipcMain.on('exit-fullscreen', () => {
      if (mainWindow.isFullScreen()) {
        mainWindow.setFullScreen(false);
        mainWindow.webContents.send('fullscreen-status', false);
      }
    });

    // 窗口关闭事件处理
    mainWindow.on('close', (event) => {
      if (!app.isQuitting) {
        event.preventDefault();
        mainWindow.hide();
        return false;
      }
      return true;
    })

    // 处理所有新窗口请求
    mainWindow.webContents.setWindowOpenHandler(({ url }) => {
      // 使用默认浏览器打开链接
      shell.openExternal(url);
      // 阻止Electron创建新窗口
      return { action: 'deny' };
    })

    // 处理导航请求（当用户点击链接时）
    mainWindow.webContents.on('will-navigate', (event, url) => {
      // 阻止Electron内部导航
      event.preventDefault();
      // 使用默认浏览器打开链接
      shell.openExternal(url);
    })
  }

  // This method will be called when Electron has finished
  // initialization and is ready to create browser windows.
  // Some APIs can only be used after this event occurs.
  app.whenReady().then(() => {
    createWindow();
    createTray();

    app.on('activate', function () {
      // On macOS it's common to re-create a window in the app when the
      // dock icon is clicked and there are no other windows open.
      const { Menu } = require('electron');
      Menu.setApplicationMenu(null);
      if (BrowserWindow.getAllWindows().length === 0) createWindow()
    })

  })

  // Quit when all windows are closed, except on macOS. There, it's common
  // for applications and their menu bar to stay active until the user quits
  // explicitly with Cmd + Q.
  app.on('window-all-closed', function () {
    if (process.platform !== 'darwin') app.quit()
  })

  // In this file you can include the rest of your app's specific main process
  // code. You can also put them in separate files and require them here.
  // 打开文件夹对话框
  ipcMain.handle('open-directory-dialog', async (event) => {
    const result = await dialog.showOpenDialog({
      properties: ['openDirectory'],
      title: '选择保存文件夹',
      defaultPath: app.getPath('downloads') // 默认下载目录
    });

    if (!result.canceled && result.filePaths.length > 0) {
      return result.filePaths[0];
    }
    return null;
  });

  // 保存设置
  ipcMain.handle('saveSettings', async (event, settings) => {
    try {
      fs.writeFileSync(SETTINGS_PATH, JSON.stringify(settings));
      return { success: true };
    } catch (error) {
      return { success: false, message: error.message };
    }
  });

  // 加载设置
  ipcMain.handle('loadSettings', async () => {
    try {
      if (fs.existsSync(SETTINGS_PATH)) {
        return JSON.parse(fs.readFileSync(SETTINGS_PATH));
      }
      return null;
    } catch (error) {
      return null;
    }
  });

  // 下载文件
  ipcMain.handle('download-file', async (event, options) => {
    try {
      const filePath = path.join(options.downloadPath, options.filename);
      const win = BrowserWindow.getFocusedWindow();

      // 使用electron-dl下载文件
      const { download } = require('electron-dl');
      await download(win, options.url, {
        directory: options.downloadPath,
        filename: options.filename,
        onProgress: (progress) => {
          win.webContents.send('download-progress', {
            id: options.id,
            percent: progress.percent * 100
          });
        }
      });

      return { success: true, filePath };
    } catch (error) {
      return { success: false, message: error.message };
    }
  });

  function createTray() {
    // 创建托盘图标
    tray = new Tray(path.join(__dirname, 'images/icon.png'));

    // 托盘提示
    tray.setToolTip('轻音乐');

    // 托盘菜单
    const contextMenu = Menu.buildFromTemplate([
      {
        label: '打开应用',
        click: () => {
          mainWindow.show();
        }
      },
      {
        label: '退出',
        click: () => {
          app.isQuitting = true;
          app.quit();
        }
      }
    ]);

    tray.setContextMenu(contextMenu);

    // 托盘图标点击事件
    tray.on('click', () => {
      if (mainWindow.isVisible()) {
        mainWindow.hide();
      } else {
        mainWindow.show();
      }
    });
  }
}
